import os

from paddleocr import PaddleOCR, draw_ocr
from werkzeug.utils import secure_filename
from flask import Flask, request, jsonify
#设置允许的文件格式
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'JPG', 'PNG', 'bmp'])
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS


app = Flask(__name__)

@app.route('/upload', methods=['POST', 'GET'])
def upload():
    if request.method == 'POST':
        user_input = request.form.get("name")
        f = request.files['file']
        if not (f and allowed_file(f.filename)):
            return jsonify({"error": 1001, "msg": "请检查上传的图片类型，仅限于png、PNG、jpg、JPG、bmp"})
        basepath = os.path.dirname(__file__)  # 当前文件所在路径
        upload_path = os.path.join(basepath, 'images', secure_filename(f.filename))  # 注意：没有的文件夹一定要先创建，不然会提示没有该路径
        f.save(upload_path)
        ocr = PaddleOCR(use_angle_cls=True, lang="ch")  # need to run only once to download and load model into memory
        img_path = upload_path
        traceCodes = ''
        result = ocr.ocr(img_path, cls=True)
        for idx in range(len(result)):
            res = result[idx]
            for line in res:
                if(line[1][0].find("发票号码")) != -1 :
                   retD =  line[1][0].split("：")
                   print(retD)
                   traceCodes = retD[1]
    # return jsonify({'traceCodes': ','.join(traceCodes)})
    return jsonify(发票号码 = traceCodes)
    # return json.dumps(','.join(traceCodes),ensure_ascii= False)

if __name__ == '__main__':
    # app.debug = True
    app.run(host='0.0.0.0', port=9008, debug=True)